package com.ruoyi.project.knowledge.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.knowledge.domain.KnowledgeAttach;
import com.ruoyi.project.knowledge.domain.KnowledgeBase;
import com.ruoyi.project.knowledge.service.IKnowledgeAttachService;
import com.ruoyi.project.knowledge.service.IKnowledgeBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/knowledge")
public class KnowledgeBaseController extends BaseController {
    @Autowired
    private IKnowledgeBaseService knowledgeService;
    @Autowired
    private IKnowledgeAttachService attachService;

    //@Value("http://localhost:8080")
    @Value("http://192.168.2.108:8089")
    private String host;

    @GetMapping("/list")
    public TableDataInfo list(KnowledgeBase knowledge)
    {
        startPage();
        List<KnowledgeBase> list = knowledgeService.selectKnowledgeList(knowledge);
        return getDataTable(list);
    }

    @GetMapping("/selectPublicKnowledgeList")
    public TableDataInfo selectPublicKnowledgeList(KnowledgeBase knowledge)
    {
        startPage();
        List<KnowledgeBase> list = knowledgeService.selectPublicKnowledgeList(knowledge);
        return getDataTable(list);
    }

    @GetMapping("/selectKnowleges/{searchValue}")
    public TableDataInfo selectKnowleges(@PathVariable("searchValue") String searchValue)
    {
        startPage();
        List<KnowledgeBase> list = knowledgeService.searchKnowledgeList(searchValue);
        return getDataTable(list);
    }

    @GetMapping("/selectKnowledgeById/{id}")
    public AjaxResult selectKnowledgeById(@PathVariable("id") String id)
    {
        return AjaxResult.success(knowledgeService.selectKnowledgeById(id));
    }

    @Log(title = "新增知识库", businessType = BusinessType.INSERT)
    @PostMapping(value = "")
    public AjaxResult insert(@RequestParam("files") MultipartFile[] files, KnowledgeBase knowledge) throws IOException
    {
        List<KnowledgeAttach> attachList = new ArrayList<>();
        if(files != null){
            for(MultipartFile file : files) {
                String filename = FileUploadUtils.upload(RuoYiConfig.getKnowledgeAttachPath(), file);
                String url = host + filename;

                KnowledgeAttach attach = new KnowledgeAttach();
                attach.setFileName(file.getOriginalFilename());
                attach.setUrl(url);
                attachList.add(attach);
            }
        }

        return knowledgeService.insertKnowledge(knowledge, attachList);
    }

    @Log(title = "修改知识库", businessType = BusinessType.UPDATE)
    @PutMapping("")
    public AjaxResult update(@RequestParam("files") MultipartFile[] files, KnowledgeBase knowledge) throws IOException
    {
        List<String> urlList = new ArrayList<>();
        if(knowledge.getAttachList() != null && knowledge.getAttachList().size() > 0) {
            urlList = knowledge.getAttachList().stream().map(KnowledgeAttach::getUrl).collect(Collectors.toList());
        }

        List<KnowledgeAttach> attchFiles = attachService.selectAttachList(knowledge.getId());
        if (attchFiles != null && attchFiles.size() > 0) {
            for (KnowledgeAttach attach : attchFiles) {
                if(!urlList.contains(attach.getUrl())){
                    // 说明文件已删除，删除本地磁盘对应的文件
                    String fileName = RuoYiConfig.getKnowledgeAttachPath() + attach.getUrl().replace(host + "/profile/knowledge/attach", "");
                    FileUtils.deleteFile(fileName);

                    // 删除数据库对应的附件
                    attachService.deleteAttach(attach.getId());
                }
            }
        }

        List<KnowledgeAttach> attachList = new ArrayList<>();
        if(files != null) {
            for (MultipartFile file : files) {
                String filename = FileUploadUtils.upload(RuoYiConfig.getKnowledgeAttachPath(), file);
                String url = host + filename;

                KnowledgeAttach attach = new KnowledgeAttach();
                attach.setFileName(file.getOriginalFilename());
                attach.setUrl(url);
                attachList.add(attach);
            }
        }

        return knowledgeService.updateKnowledge(knowledge, attachList);
    }

    @Log(title = "删除知识库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") String id)
    {
        return AjaxResult.success(knowledgeService.deleteKnowledge(id));
    }

    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file) throws IOException
    {
        JSONObject result = new JSONObject();

        String filename = FileUploadUtils.upload(RuoYiConfig.getKnowledgeContentPath(), file);
        String url = host + filename;

        result.put("link", url);
        result.put("originalName", file.getOriginalFilename());
        result.put("name", file.getName());

        return AjaxResult.success(result);
    }

    @PostMapping("/uploadAttachFile")
    public AjaxResult uploadAttachFile(MultipartFile file) throws IOException
    {
        JSONObject result = new JSONObject();

        String filename = FileUploadUtils.upload(RuoYiConfig.getKnowledgeAttachPath(), file);
        String url = host + filename;

        result.put("link", url);
        result.put("originalName", file.getOriginalFilename());
        result.put("name", file.getName());

        return AjaxResult.success(result);
    }

    @PostMapping("/deleteAttachFile")
    public AjaxResult deleteAttachFile(@RequestBody KnowledgeAttach attach)
    {
        if(StringUtils.isNotEmpty(attach.getUrl())){
            String fileName = RuoYiConfig.getKnowledgeAttachPath() + attach.getUrl().replace(host + "/profile/knowledge/attach", "");
            FileUtils.deleteFile(fileName);
        }else {
            List<KnowledgeAttach> attachList = attachService.selectAttachList(attach.getKnowledgeId());
            if (attachList != null && attachList.size() > 0) {
                for (KnowledgeAttach a : attachList) {
                    if (a.getFileName().equals(attach.getFileName())) {
                        String fileName = RuoYiConfig.getKnowledgeAttachPath() + a.getUrl().replace(host + "/profile/knowledge/attach", "");
                        FileUtils.deleteFile(fileName);
                        break;
                    }
                }
            }
        }

        return AjaxResult.success("删除成功！");
    }
}
